package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileController {

    @Value("${reggie.file-path}")
    private String path;


    @PostMapping("/common/upload")
    public R<String> upload(MultipartFile file) {
        //接收从网页来的文件，因为现在还处于临时文件，
        try {
            String originalFilename = file.getOriginalFilename();
            //获得后缀名
            String substring = originalFilename.substring(originalFilename.indexOf("."));

            String s = UUID.randomUUID().toString().replace("-", "") + substring;
            //判断文件目录是否已存在
            File file1 = new File(path);
            if (!file1.exists()) {
                //如果没有，新建一个文件目录
                file1.mkdirs();
            }
            File f = new File(path + s);
            //文件转移到这
            file.transferTo(f);

            return R.success(s);
        } catch (IOException e) {
            e.printStackTrace();
            return R.success("上传失败");
        }

    }
    @GetMapping("/common/download")
    public R download(String name, HttpServletResponse response){
        try {
            File file = new File(path+name);

            FileInputStream fileInputStream = new FileInputStream(file);

            ServletOutputStream outputStream = response.getOutputStream();

            byte[] buffer = new byte[1024];

            int len =0;
            while((len=fileInputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,len);
                outputStream.flush();
            }

            outputStream.close();
            fileInputStream.close();

            return R.success("成功");
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("失败");
        }


    }
}
